package com.semeureka.fault.dao.impl;

import java.util.Date;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.semeureka.fault.bean.Device;
import com.semeureka.fault.bean.Device.Phase;
import com.semeureka.fault.bean.Group;
import com.semeureka.fault.dao.DeviceDao;

@Component
public class DeviceDaoImpl implements DeviceDao {
	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public Device findByCode(byte[] code) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Device.class);
		criteria.add(Restrictions.eq("code", code));
		return (Device) criteria.uniqueResult();
	}

	@Override
	public Device findByGroupPhase(Group group, Phase phase) {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Device.class);
		if (Phase.M.equals(phase)) {// 是通讯主机时查询唯一具有相同通讯主机编码的M项设备
			criteria.createAlias("group", "Group");
			criteria.add(Restrictions.eq("Group.hostCode", group.getHostCode()));
		} else {
			criteria.add(Restrictions.eq("group", group));
		}
		criteria.add(Restrictions.eq("phase", phase));
		return (Device) criteria.uniqueResult();
	}

	@Override
	public void updateTime(Group group, Phase phase, Date createTime) {
		if (Phase.M.equals(phase)) { // 是通讯主机时更新所有具有相同通讯主机编码的M项设备
			String queryString = "update Device d set d.updateTime = :updateTime"
					+ " where d.group in (from Group g where d.group.hostCode = :hostCode) and d.phase = :phase"
					+ " and (d.updateTime is null or d.updateTime < :updateTime)";
			sessionFactory.getCurrentSession().createQuery(queryString)
					.setParameter("hostCode", group.getHostCode()).setParameter("phase", phase)
					.setParameter("updateTime", createTime)
					.executeUpdate();
		} else {
			String queryString = "update Device d set d.updateTime = :updateTime"
					+ " where d.group = :group and d.phase = :phase"
					+ " and (d.updateTime is null or d.updateTime < :updateTime)";
			sessionFactory.getCurrentSession().createQuery(queryString)
					.setParameter("group", group).setParameter("phase", phase)
					.setParameter("updateTime", createTime)
					.executeUpdate();
		}
	}
}
